/*
 * Android Runner is a multiplayer GPS game fully written by Xurxo Mendez Perez
 * 
 * Copyright (C) 2009 Xurxo Mendez Perez
 *   
 * This file is part of Android Runner.
 * 
 * Android Runner is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Android Runner is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Android Runner.  If not, see <http://www.gnu.org/licenses/>.
 */

package es.sonxurxo.gpsgame.client.cv.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import es.sonxurxo.gpsgame.client.R;
import es.sonxurxo.gpsgame.client.cv.common.actions.CommonActions;
import es.sonxurxo.gpsgame.client.cv.common.dialogs.CommonDialogs;
import es.sonxurxo.gpsgame.client.cv.util.constants.Countries;
import es.sonxurxo.gpsgame.client.model.service.player.HttpPlayerServiceImpl;
import es.sonxurxo.gpsgame.client.model.service.to.Player;
import es.sonxurxo.gpsgame.client.util.exception.ServerException;

/**
 * 
 * @author "Xurxo Mendez Perez"
 *
 */
public class UpdateInfoActivity extends Activity {

	private static final int LOGOUT_ID = Menu.FIRST;
    private static final int UPDATE_ID = Menu.FIRST + 1;

    private static final int CHANGE_IMAGE_REQUEST_CODE = 0;
    
    private Player player;
	private int imageId;

    private TextView loginView;
    private AutoCompleteTextView countryText;
    private EditText nameText, surnameText, emailText, phoneText;
    private CheckBox showEmailCB;
    private ImageView image;
	private Button updateButton;
    
	private UpdateTask updateTask;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.update_info_page);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_1);
        
        Bundle extras = getIntent().getExtras();
        
		player = (Player)extras.getSerializable("player");
		((TextView)findViewById(R.id.title_right_text)).setText(player.getLogin());
		
        loginView = (TextView)findViewById(R.id.ui_tv_login);
        loginView.setText(player.getLogin());
        
        emailText = (EditText)findViewById(R.id.ui_et_email);
        emailText.setText(player.getEmail());
        
        phoneText = (EditText)findViewById(R.id.ui_et_phone);
        phoneText.setText(player.getPhone());
        
        showEmailCB = (CheckBox)findViewById(R.id.ui_show_email);
        showEmailCB.setChecked(player.isShowPersonalInfo());
        
        nameText = (EditText)findViewById(R.id.ui_et_name);
        nameText.setText(player.getName());
        
        surnameText = (EditText)findViewById(R.id.ui_et_surname);
        surnameText.setText(player.getSurname());
        
        countryText = (AutoCompleteTextView) findViewById(R.id.ui_et_country);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, Countries.COUNTRIES);
        countryText.setAdapter(adapter);
        countryText.setText(player.getCountry());

        image = (ImageView) findViewById(R.id.up_image);
        imageId = player.getImageId();
        image.setImageResource(imageId);
        
        image.setOnLongClickListener(new OnLongClickListener() {

			public boolean onLongClick(View arg0) {
				doChangeImage();
				return true;
			}
        });
        
        updateButton = (Button)findViewById(R.id.ui_b_update);
        updateButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				launchUpdateThread();
			}        	
        });
    }
    
    private void showToast(int messageId, int length) {
		Toast.makeText(this, messageId,
                length).show();
	}
    
    private void doLogout() {
		CommonActions.launchLogoutThread(player.getLogin(), this);
	}
    
    private void doUpdate() {
    	Intent mIntent = new Intent();
		Bundle bundle = new Bundle();
		bundle.putSerializable("player", player);
		mIntent.putExtras(bundle);
    	setResult(RESULT_OK, mIntent);
		finish();
    }
    
    private void launchUpdateThread() {
    	String email = emailText.getText().toString();
    	boolean showPersonalInfo = showEmailCB.isChecked();
    	String phone = phoneText.getText().toString();
    	String name = nameText.getText().toString();
		String surname = surnameText.getText().toString();
		String country = countryText.getText().toString();

		if (email.equals("") || phone.equals("") || name.equals("") || surname.equals("") || country.equals("")) {
			showToast(R.string.pi_wrong_fields, Toast.LENGTH_SHORT);
			return;
		}
		
		updateTask = new UpdateTask(email, phone, name, 
				surname, country, showPersonalInfo, imageId);
		Thread loginThread = new Thread(null, updateTask, "Login");
		loginThread.start();
		showDialog(CommonDialogs.CONNECTING_TO_SERVER_DIALOG_ID);
	}
    
    private void doChangeImage() {
		Intent i = new Intent(this, ChangeImageActivity.class);
		startActivityForResult(i, CHANGE_IMAGE_REQUEST_CODE);
	}
    
    @Override
    protected Dialog onCreateDialog(int id) {
    	return CommonDialogs.createDialog(id, this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, LOGOUT_ID,0, R.string.pi_mo_logout)
        	.setIcon(R.drawable.logout);
        menu.add(0, UPDATE_ID,0, R.string.pi_b_update_info)
        	.setIcon(R.drawable.update);
        return true;
    }
	
	@Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
        case LOGOUT_ID:
        	doLogout();
        	break;
        case UPDATE_ID:
        	launchUpdateThread();
        	break;
        }
        return super.onMenuItemSelected(featureId, item);
    }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch(requestCode) {
		case CHANGE_IMAGE_REQUEST_CODE:
			switch(resultCode) {
			case RESULT_OK:
				imageId = data.getExtras().getInt("imageId");
				player.setImageId(imageId);
				image.setImageResource(imageId);
			}
			break;
		}
	}
	
	private class RegisterHandler extends Handler {

		public RegisterHandler(Looper looper) {
			super(looper);
		}
		
		@Override
		public void handleMessage(Message msg) {
			ServerException sE = 
				(ServerException)msg.getData().getSerializable("ServerException");			
			if (sE	!= null) {
				dismissDialog(CommonDialogs.CONNECTING_TO_SERVER_DIALOG_ID);
				CommonDialogs.errorMessage = sE.getMessage();
				if (sE.getCode() == ServerException.INSTANCE_NOT_FOUND_CODE)
					showDialog(CommonDialogs.CONNECTION_LOST_DIALOG_ID);
				else
					showDialog(CommonDialogs.SERVER_ERROR_DIALOG_ID);
	        	return;
	        }
        	Exception e = 
	        	(Exception)msg.getData().getSerializable("Exception");
	        	if (e != null) {
	        		dismissDialog(CommonDialogs.CONNECTING_TO_SERVER_DIALOG_ID);
	        		CommonDialogs.errorMessage = e.getMessage();
		        	showDialog(CommonDialogs.CLIENT_ERROR_DIALOG_ID);
		        	return;
	        	}
			Player player2 = (Player)msg.getData().getSerializable("player");
			if (player2 != null) {
	        	player = player2;
	        	doUpdate();
	        }
		}
	}
	
	private class UpdateTask implements Runnable {

		String email, phone, name, surname, country;
		boolean showPersonalInfo;
		int imageId;
		HttpPlayerServiceImpl playerService;

		public UpdateTask(String email,	String phone, String name, String surname, 
				String country,	boolean showPersonalInfo, int imageId) {
			super();
			this.email = email;
			this.phone = phone;
			this.name = name;
			this.surname = surname;
			this.country = country;
			this.showPersonalInfo = showPersonalInfo;
			this.imageId = imageId;
			playerService = new HttpPlayerServiceImpl();
		}

		public void run() {
			
			RegisterHandler handler = new RegisterHandler(Looper.getMainLooper());
			Bundle data = new Bundle();
			Message msg = new Message();
			try {
				
				playerService.updatePlayer(
						email, showPersonalInfo, phone, 
						name, surname, country, imageId);
				player.setEmail(email);
				player.setShowPersonalInfo(showPersonalInfo);
				player.setPhone(phone);
				player.setName(name);
				player.setSurname(surname);
				player.setCountry(country);
				player.setImageId(imageId);
				data.putSerializable("player", player);
				msg.setData(data);
				handler.sendMessage(msg);
				
			} catch (ServerException e) {
	        	data.putSerializable("ServerException", e);
	        	msg.setData(data);
				handler.sendMessage(msg);
	        } catch (Exception e) {
	        	data.putSerializable("Exception", e);
	        	msg.setData(data);
				handler.sendMessage(msg);
	        }
		}
	}

}
